package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;
        //获取购物车中所有商品的信息列表
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        //获取所有商品的id---此时是空的，因为购物车并没有传递这样的数据过来
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();
        //通过购物车商品列表给商品idlist赋值
        if (CollectionUtils.isEmpty(buyProductIds)) {
            buyProductIds =new ArrayList<Long>();
            for (CartProductDto cartProductDto : cartProductDtoList) {
                Long productId = cartProductDto.getProductId();
                buyProductIds.add(productId);
            }
        }
        buyProductIds.sort(Long::compareTo);

        //TODO：关键步骤1：锁定库存-->扣减库存
        //该方法锁定库存
        List<Stock> stocksForUpdate = stockMapper.findStocksForUpdate(buyProductIds);
        if (CollectionUtils.isEmpty(stocksForUpdate)){
            throw  new BizException("库存没有初始化");//TODO:这里应优化一下
        }
        if(stocksForUpdate.size()!=buyProductIds.size()){
            throw  new BizException("部分库存没有初始化");//TODO:这里应优化一下
        }
        //扣减库存
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();//TODO:优化，不能超出限购的数量
            Stock stock = new Stock();
            stock.setItemId(productId);
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            stockMapper.updateStock(stock);
        }
        return true;
    }
}